<template>
  <div class="search-tree-com-wrapper">
    <!-- 设备树 -->
    <div
      :class="['tree-list', { 'tree-list-empty': treeData.length === 0 }]"
      @click="
        topMenuVisible = false;
        contextMenuType = 0;
      "
    >
      <dpro-tree
        class="my-tree"
        v-if="showTree"
        :load-data="onLoadData"
        :tree-data="treeData"
        :selectedKeys="selectedKeys"
        :expandedKeys="expandedKeys"
        :loadedKeys="loadedKeys"
        showIcon
        :checkable="isCheckBox"
        :checkedKeys="checkedKeys"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand"
        @rightClick="rightClick"
      >
        <span class="custom-sw-icon icon-iCON_flod" slot="switcherIcon"></span>
        <template slot="titleIcon">
          <span class="icon-sprite icon-iCON_location_online_normal"></span>
        </template>
        <template slot="deviceIcon">
          <img
            class="icon-device"
            :src="require('./assets/iCON_Divers_online_normal-nocloud.png')"
          />
        </template>
        <!-- 加载更多按钮节点 -->
        <template slot="loadTitle" slot-scope="dataRef">
          <p class="menu-title" @click="loadMore(dataRef)">
            {{ dataRef.title }}
          </p>
        </template>
        <template slot="title" slot-scope="dataRef">
          <p
            :id="dataRef.key"
            class="menu-title"
            @click="clickNode(dataRef)"
            @dblclick="dbclickNode(dataRef)"
          >
            <span
              v-if="
                dataRef.searchFirstLevel &&
                dataRef.title.indexOf(searchText) > -1
              "
              >{{ dataRef.title.substr(0, dataRef.title.indexOf(searchText))
              }}<span class="color-match">{{ searchText }}</span
              >{{
                dataRef.title.substr(
                  dataRef.title.indexOf(searchText) + searchText.length
                )
              }}</span
            ><span v-else>{{ dataRef.title }}</span
            >{{
              dataRef.searchFirstLevel || dataRef.deviceCode
                ? ""
                : ` (${dataRef.onlineDeviceCount || 0}/${
                    dataRef.deviceCount || 0
                  })`
            }}
          </p>
        </template>
      </dpro-tree>
      <div
        class="tree-empty"
        v-if="treeData.length === 0 && !loading.getSearchTreeLoading"
      >
        <!-- <img class="img-empty" src="@/assets/iCON_ListNo.png" /> -->
        <div class="text">暂无搜索结果</div>
      </div>
      <a-spin class="tree-loading" v-if="loading.getSearchTreeLoading" />
      <!-- <a-spin class="tree-loading" /> -->

    </div>
    <!-- <template slot="overlay">
        <a-menu @click="topMenuVisible = false">
          <a-menu-item @click="refreshTree">刷新组织树</a-menu-item>
        </a-menu>
      </template> -->
    <div class="footer" v-if="showMore">
      <a-button
        type="primary"
        class="btn-search-more"
        @click="loadMoreSearch"
        :disabled="!!loading.getSearchTreeLoading"
        >加载更多</a-button
      >
    </div>
  </div>
</template>

<script>
import { flatten } from "@/utils/util";
import searchTreeMixin from "./search-tree-mixin";
import { DproTree } from "../../components/index";

export default {
  name: "SearchTreeCom",
  props: [
    "siderEl",
    "searchText",
    "searchType",
    "isCheckBox",
    "cardInfo",
    "checkedKeys",
  ],
  data() {
    return {
      showTree: true,
      contextMenuType: 0, // 右键菜单类型，0不显示，1显示分组菜单，2显示设备菜单
      rightClickItem: null, // 右键菜单
      // checkedKeys: [],
      selectedKeys: [],
      // loadedKeys: [],// 已加载的节点
      topMenuVisible: false,
      treeData: [],
      showMore: false,
      loading: false,
      searchSortArr: "", // 搜索结果分页请求参数
    };
  },
  mixins: [searchTreeMixin],
  components: {
    DproTree,
  },
  computed: {
    reginMenus() {
      return [];
    },
    deviceMenus() {
      return [
        // {
        //   title: '刷新组织树',
        //   key: 'device-menu-3',
        //   hidden: false
        // },
        {
          title: "获取设备信息",
          key: "device-menu-4",
          hidden: false,
        },
      ];
    },
    loadedKeys() {
      return flatten(this.treeData)
        .map((item) => {
          return item.children ? item.key : "";
        })
        .filter((key) => key);
    },
    // 当前已请求的所有设备
    flattenDeviceList() {
      return flatten(this.treeData).filter((item) => item.deviceCode);
    },
  },
  mounted() {
    // if (!this.treeData || this.treeData.length === 0) {
    //   this.getTreeData();
    // }
    // eventBus.$on("locatedToTree", this.locatedToTree);
  },
  beforeDestroy() {
    // eventBus.$off("locatedToTree", this.locatedToTree);
  },
  methods: {
    search() {
      this.treeData = [];
      this.selectedKeys = [];
      this.expandedKeys = [];
      this.searchSortArr = "";
      this.showMore = false;
      return this.getTreeData();
    },
    // 展开设备树某个列表
    onLoadData(treeNode) {
      // console.log('onLoadData')
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          // console.log('children已存在')
          resolve();
          return;
        }
        let params = {
          parentId: treeNode.dataRef.regionCode,
          isGetDeviceList: treeNode.dataRef.havDevice === 1,
          hasChildren: treeNode.dataRef.hasChildren,
          parentRealRegionCode: treeNode.dataRef.realRegionCode,
        };
        this.getTreeData(params).finally(() => {
          resolve();
        });
      });
    },
    // 分页加载更多设备
    loadMore(dataRef) {
      if (
        !dataRef.parentNodeDataRef?.regionCode ||
        this.loading.getSearchTreeLoading
      )
        return;
      let params = {
        parentId: dataRef.parentNodeDataRef.regionCode,
        isGetDeviceList: true,
        hasChildren: false, // 只请求设备节点，不请求目录节点
        pageNo: dataRef.nextPage,
        showLoading: true,
        parentRealRegionCode: dataRef.parentNodeDataRef.realRegionCode,
      };
      this.getTreeData(params);
    },
    // 分页获取更多搜索结果
    loadMoreSearch() {
      this.getTreeData();
    },
    // 选择视频设备
    async onCheck(checkedKeys, event) {
      this.$emit("check", checkedKeys, this.flattenDeviceList, event);
    },
    // 选择视频设备
    onSelect(selectedKeys, event) {
      // console.log(event.node.dataRef);
      this.contextMenuType = 0;
      this.selectedKeys = [event.node.dataRef.key]; // 不允许点击两次取消选择
      // if (event.node.dataRef && event.node.dataRef.deviceCode) {
      //   // 选择了摄像头设备
      //   let deviceInfo = event.node.dataRef;
      //   this.setSelectedDevice(deviceInfo); // 存储选择状态
      // }
      this.$emit("select", event.node.dataRef, event);
    },
    // 双击
    dbclickNode(dataRef) {
      if (dataRef.deviceCode) {
        this.$emit("select", dataRef);
      }
    },

    // 右击
    rightClick({ event, node }) {
      this.contextMenuType = 0;
      this.$nextTick(() => {
        this.topMenuVisible = false;
        event.stopPropagation();
        this.rightClickItem = node.dataRef;
        if (node.dataRef.regionCode) {
          // 显示区域菜单
          this.contextMenuType = 1;
          this.selectedKeys = [node.dataRef.key];
        } else if (node.dataRef.deviceCode) {
          // 显示设备菜单
          this.contextMenuType = 2;
          this.selectedKeys = [node.dataRef.key];
          this.setSelectedDevice(node.dataRef);
        } else {
          this.contextMenuType = 0;
        }
      });
    },

    // 点击分组菜单选项
    clickReginMenu({ key }) {
      let { regionCode } = this.rightClickItem || {};
    },

    // 点击设备菜单选项
    clickDeviceMenu({ key }) {
      let { deviceCode } = this.rightClickItem || {};
      if (deviceCode) {
        switch (key) {
          // case 'device-menu-3':
          //   console.log('device-menu-3');
          //   // 刷新组织树
          //   this.refreshTree();
          //   break;
          case "device-menu-4":
            console.log("device-menu-4");
            // 获取设备信息
            this.showDeviceInfo();
            break;
        }
      }
    },
    // 刷新当前节点
    refreshCurrentRegin() {
      if (!this.rightClickItem) return;
      let reginItem = this.rightClickItem;
      // 关闭该节点下已展开的节点
      this.collspandRelativeKeys(reginItem.key);

      let params = {
        parentId: reginItem.regionCode,
        isGetDeviceList: reginItem.havDevice === 1,
        hasChildren: reginItem.hasChildren,
        showLoading: true,
        refreshNode: true,
        parentRealRegionCode: reginItem.realRegionCode,
      };
      this.getTreeData(params);
    },
    // 关闭某节点下已展开的节点
    collspandRelativeKeys(key) {
      let exKeyPaths = [];
      // console.log('expandedKeys:',this.expandedKeys)
      this.expandedKeys.forEach((exKey) => {
        let res = this.getItemByKey(exKey, this.treeData);
        res && exKeyPaths.push(res.keyPath);
      });
      // console.log('exKeyPaths:',exKeyPaths)
      exKeyPaths.forEach((item) => {
        let arr = item.split("/");
        arr && arr.length > 0 && arr.pop();
        if (arr.includes(String(key))) {
          // 删除key下已展开的子节点
          let deleteKey = item.substring(item.lastIndexOf("/") + 1);
          // console.log('expandedKeys-deleteKey:',deleteKey);
          this.expandedKeys.forEach((item, index) => {
            if (item === deleteKey) this.expandedKeys.splice(index, 1);
          });
        }
      });
      // console.log('af-expandedKeys:',this.expandedKeys)
    },
    // 根据key获取item
    getItemByKey(key, tree) {
      let item = tree.find((item) => item.key === key);
      if (!item) {
        // 查找深层子节点
        for (let i = 0, len = tree.length; i < len; i++) {
          let itm = tree[i];
          if (itm.children && itm.children.length > 0) {
            item = this.getItemByKey(key, itm.children);
            if (item) break;
          }
        }
      }
      // item && console.log(`${key}的keyPath：${item.keyPath}`)
      return item;
    },
    // 刷新分组数组
    async refreshTree() {
      this.treeData = [];
      this.selectedKeys = [];
      this.expandedKeys = [];
      this.searchSortArr = "";
      this.showMore = false;
      this.showTree = false;
      await this.$nextTick();
      this.showTree = true;
      await this.getTreeData();
    },

    // 查询设备信息
    showDeviceInfo() {
      // 数据兼容
      this.rightClickItem.data = this.rightClickItem;
      this.$refs.deviceInfoModal &&
        this.$refs.deviceInfoModal.open(this.rightClickItem);
    },

    // 定位到树
    locatedToTree(deviceCode) {
      let deviceInfo = this.flattenDeviceList.find(
        (item) => item.deviceCode === deviceCode
      );
      // console.log('定位到树:',deviceCode,deviceInfo);
      if (deviceInfo?.keyPath) {
        let parentKeys = deviceInfo.keyPath.split("/");
        parentKeys.splice(-1, 1);
        // console.log('父节点:',parentKeys);
        // 展开节点
        this.addToExpand(parentKeys);
        // 选中设备
        this.selectedKeys = [deviceInfo.key];
        this.setSelectedDevice(deviceInfo);

        this.$nextTick(() => {
          document.getElementById(deviceInfo.key)?.scrollIntoView();
        });
      }
    },

    // 展开节点
    addToExpand(keys = []) {
      keys.forEach((key) => {
        if (!this.expandedKeys.includes(key)) {
          this.expandedKeys.push(key);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search-tree-com-wrapper {
  .footer {
    text-align: center;
    padding: 4px;
  }
  .btn-search-more {
    width: 80%;
  }
}
.tree-list {
  position: relative;
  // overflow: hidden;
  &.tree-list-empty {
    min-height: 100px;
  }
  .my-tree {
    position: relative;
    height: 100%;
    // overflow: auto;
    padding-left: 12px;
    .menu-title {
      margin-bottom: 0;
      display: inline-block;
      min-width: 160px;
      user-select: none;
    }
    /deep/ li span.ant-tree-switcher.ant-tree-switcher-noop {
      margin-left: 0;
    }
  }
  .tree-empty {
    position: absolute;
    top: 45%;
    left: 50%;
    width: 100%;
    transform: translate3d(-50%, -50%, 0);
    text-align: center;

    .img-empty {
      width: 58px;
      height: 58px;
    }

    .text {
      margin-top: 6px;
      font-size: 12px;
      opacity: 0.6;
    }

    button {
      width: 120px;
      margin-top: 16px;
    }
  }
  .tree-loading {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%, -50%, 0);
  }
  .context-block {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
.icon-device {
  width: 24px;
  height: 24px;
}
</style>
